import zmail
import unittest
from datetime import datetime
from bs4 import BeautifulSoup
from xbd.publics.HTMLTestRunner import HTMLTestRunner


class PublicRunCases():

    def send_email(self, file, receiver, subject, type='zmail'):
        '''发邮件:file附件路径，receiver收件人邮箱列表，subject邮件主题，zmail、yagmail使用不同库发送'''
        user = '2867148956@qq.com'  # 发件人邮箱
        paw = 'hvooikvymaqddgdd'  # 发件人SMTP授权码
        # 读取html，replace去除换行符不然有很多空白行
        html = BeautifulSoup(open(file, encoding='utf-8'), features='html.parser')
        html = str(html).replace("\n", "")
        if type == 'zmail':
            server = zmail.server(username=user, password=paw)
            mail = {
                'content_html': html,  # 正文
                'attachments': file,  # 附件
                'subject': subject,  # 主题
                'from': '"=?utf-8?B?5pa55bGV6LGq=?=" <2867148956@qq.com>',
                # 设置发件人名称，中文需base64编码（参考https://service.mail.qq.com/detail/124/995）
            }
            server.send_mail(receiver, mail)
        elif type == 'yagmail':
            server = yagmail.SMTP(user=user, password=paw, host='smtp.qq.com')
            server.send(
                contents = html,  # 正文
                to = receiver,  # 收件人邮箱
                attachments = file,  # 附件路径
                subject = subject,  # 主题
                headers = {'From': '方展豪'}  # 发件人名称
            )
        server.close()

    def runcases(self, flie_name, case=['*']):
        '''*是运行test_cases中所有用例，x则是运行test_cases中文件名为x中的所有用例'''
        suite = unittest.TestSuite()
        for i in case:
            discover = unittest.defaultTestLoader.discover("./test_cases/", i + '.py')
            suite.addTests(discover)
        report = f'./reports/' + flie_name + datetime.now().strftime("%Y-%m-%d %H_%M_%S") + '.html'
        # 把测试结果写进测试报告，并装载到HTHMLTestRunner模块，titl是HTML标题
        runner = HTMLTestRunner(stream=open(report, "wb"), title=flie_name)
        runner.run(suite)  # 运行测试套里的用例
        return report  # 返回报告的完整路径，用于发送邮件时添加附件



